using UnityEngine;

public class BulletFrag : MonoBehaviour
{
    public string targetTag = "Enemy";
    public float initialSpeed = 7f; // 初始速度
    public Vector3 torque = new Vector3(0f, 1f, 2f); // 旋转力向量
    public float torqueMagnitude = 5f; // 旋转力大小
    public float bombTime = 3f; // 爆炸时间
    public GameObject bombEffect; // 爆炸效果预制体
    public float explosionRadius = 5f; // 爆炸半径
    public int damage = 10; // 伤害值

    private Rigidbody rigi;

    void Start(){
        rigi = GetComponent<Rigidbody>();
        float angle = 45f * Mathf.Deg2Rad; // 计算抛射角度（45度）
        // 计算初始速度向量
        Vector3 velocity = transform.forward * initialSpeed * Mathf.Cos(angle);
        velocity.y = initialSpeed * Mathf.Sin(angle);
        rigi.velocity = velocity; // 应用力
        rigi.AddTorque(torque * torqueMagnitude); // 应加旋转力
        Invoke(nameof(Explode), bombTime);// 设置爆炸定时器
    }

    void Explode(){
        if (bombEffect != null){// 创建爆炸效果
            Instantiate(bombEffect, transform.position, transform.rotation);
            ShakeMgr.ins.OnShake();
        }

        // 使用 OverlapSphere 检测爆炸范围内的目标
        Collider[] hitColliders = Physics.OverlapSphere(transform.position, explosionRadius);
        foreach (Collider collider in hitColliders){
            var obj = collider.gameObject;
            if (obj.tag == targetTag) obj.SendMessage("hurt", damage);
        }
        Destroy(gameObject);// 销毁子弹对象
    }
}